package com.sky.task;

import com.sky.dto.OrdersPaymentDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
@RequiredArgsConstructor
public class OrderTask {

    private final OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 0 * * * *")
    public void cancelUnpayPayment(){
        log.info("超时订单处理：{}",new Date());

//        order_time <= date_sub(now(),interval 15 minute)
        List<Orders> unpayList = orderMapper.getByStatusAndOrderTimeLE(LocalDateTime.now().plus(-15, ChronoUnit.MINUTES),Orders.PENDING_PAYMENT);
        unpayList.forEach( u ->{
           u.setStatus(Orders.CANCELLED);
           u.setCancelReason("订单超时，自动取消");
           u.setCancelTime(LocalDateTime.now());
            orderMapper.update(u);
        });
    }

    /**
     *
     */
    @Scheduled(cron = "0 0 1 * * *")
    public void finishDeliveryOrder(){
        log.info("凌晨一点处理派送中订单，{}",new Date());
//        select * from orders where status


        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLE(LocalDateTime.now().plus(-60, ChronoUnit.MINUTES), Orders.DELIVERY_IN_PROGRESS);
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        });
    }
}
